package com.lingjtx.common.thread.mq;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONFactory;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.reader.ObjectReaderProvider;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;

import java.nio.charset.StandardCharsets;
import java.util.List;

public class FastJsonAutoTypeMessageConverter implements MessageConverter {

    private static final String DEFAULT_CHARSET = "UTF-8";

    public FastJsonAutoTypeMessageConverter(List<String> whitelistPackages) {

        // 注册自动类型识别处理器
        ObjectReaderProvider provider = JSONFactory.getDefaultObjectReaderProvider();
        provider.setAutoTypeBeforeHandler(new SafeAutoTypeHandler(whitelistPackages));
    }

    @Override
    public Message toMessage(Object object, MessageProperties messageProperties) throws MessageConversionException {
        // 开启 WriteClassName，方便反序列化时恢复类型
        byte[] body = JSON.toJSONString(object, JSONWriter.Feature.WriteClassName)
                .getBytes(StandardCharsets.UTF_8);
        messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
        messageProperties.setContentEncoding(DEFAULT_CHARSET);
        messageProperties.setContentLength(body.length);
        return new Message(body, messageProperties);
    }

    @Override
    public Object fromMessage(Message message) throws MessageConversionException {
        byte[] body = message.getBody();
        String json = new String(body, StandardCharsets.UTF_8);
        return JSON.parse(json); // Fastjson2 会根据 WriteClassName 自动识别类型
    }
}
